<template>
  <div id="batch">
    <div class="content">
      <div class="overflow-auto">
        <div class="body">
          <div class="reminder">
            <span>请注意：途家、美团、飞猪最多修改180天，爱彼迎可修改365天，您可以选择较长的日期范围，但超过渠道限制的修改不会执行。</span>
            <el-button type="text">
              <i class="el-icon-close" style="color:#606266"></i>
            </el-button>
          </div>
          <!-- 渠道 -->
          <div class="select">
            <div>1.选择渠道</div>
            <div class="select_top">
              <div class="select_num">已选 {{ checkedChannel.length }} 个渠道</div>
              <el-button type="text" @click="reset('channel')" size="small">重置</el-button>
            </div>
            <div class="select_checkbox">
              <div>
                <el-checkbox size="small" v-model="isAllCheckChannel" @change="checkAllChannel">全选</el-checkbox>
              </div>
              <el-checkbox-group size="small" v-model="checkedChannel" @change="handleCheckedChannelsChange">
                <el-checkbox v-for="channel in channels" :label="channel.name" border
                  :key="channel.channel_id"></el-checkbox>
                <!-- @change="SelectChannel(channel)" -->
              </el-checkbox-group>
            </div>
          </div>
          <!-- 选择房型 -->
          <div class="select">
            <div>2.选择房型</div>
            <div class="select_top">
              <div class="select_num">已选 {{ checkedRoom.length }} 个房型，对应 {{ checkedChannel.length }} 个渠道的房型</div>
              <el-button type="text" @click="reset('room')" size="small">重置</el-button>
            </div>
            <div class="select_checkbox">
              <div>
                <el-checkbox :disabled="roomType.length == 0" v-model="isAllCheckRoom"
                  @change="checkAllRoom">全选</el-checkbox>
              </div>
              <div v-if="checkedChannel.length == 0" style="font-size:14px; color:#0486fe">请先选择渠道</div>
              <el-checkbox-group v-else v-model="checkedRoom" size="small" @change="handleCheckedRoomsChange">
                <el-checkbox v-for="room in roomType" :label="room.pms_title" border :key="room.id"></el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <!-- 日期 -->
          <div class="select">
            <div>3.选择日期</div>
            <div class="select_top">
              <div class="select_num">已选 {{ selectDays }} 天</div>
              <el-button type="text" @click="reset('date')">重置</el-button>
            </div>
            <div class="select_date">
              <!-- 适用日期 -->
              <div class="select_date_time">
                <div style="width: 70px;">适用日期</div>
                <div class="select_date_select">
                  <div class="select_date_picker">
                    <div class="select_date_picker_item" v-for="(item, index) in dateRange" :key="index">
                      <el-date-picker size="small" style="width: 240px;" v-model="dateRange[index]" type="daterange"
                        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
                      </el-date-picker>
                    </div>
                  </div>
                  <div class="select_date_addTime">
                    <el-button type="text" @click="addDateRange">
                      <i class="el-icon-circle-plus-outline"></i>
                      添加日期段
                    </el-button>
                    <span>最多添加十个</span>
                  </div>
                </div>
              </div>
              <!-- 适用周几 -->
              <div class="select_date_time">
                <div style="width: 70px;">适用周几</div>
                <div class="select_date_select">
                  <div class="select_date_picker">
                    <el-checkbox v-model="isAllCheckWeek" @change="checkAllWeek">全选</el-checkbox>
                  </div>
                  <el-checkbox-group size="small" v-model="checkedWeek" @change="handleCheckedWeeksChange">
                    <el-checkbox v-for="week in weeks" :label="week.week_title" border :key="week.week_id"></el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>
          <!-- 调价 -->
          <div class="select">
            <div>4.设置价格</div>
            <div class="setPrice">
              <!-- 改价方式 -->
              <div class="setPrice_type">
                <div>改价方式</div>
                <div class="setPrice_type_radio">
                  <el-radio-group v-model="type" style="margin: 0px;">
                    <el-radio :label="1">指定金额</el-radio>
                    <el-radio :label="2">规则调价</el-radio>
                  </el-radio-group>
                </div>
              </div>
              <!-- 设置价格 -->
              <div class="setPrice_price">
                <div style="width: 120px;">价格统一设置为</div>
                <!-- 指定金额 -->
                <div v-show="type == 1" class="setPrice_price_appoint">
                  <el-input size="small" style="width: 140px;" placeholder="请输入指定金额" @blur="setAppointPrice_ToTable"
                    v-model="setAppointPrice">
                    <span slot="prefix">￥</span>
                  </el-input>
                </div>
                <!-- END指定金额 -->
                <!-- 规则调价 -->
                <div v-show="type == 2" class="setPrice_price_rule">
                  <div>
                    <el-select size="small" style="width: 150px;" @change="rule_channelChange"
                      v-model="rule_channel_value" placeholder="清选择">
                      <el-option v-for="item in channels" :key="item.channel_id" :label="item.name"
                        :value="item.channel_id">
                      </el-option>
                    </el-select>
                  </div>
                  <div>
                    <el-select size="small" style="width: 130px;" @change="rule_algorithmChange"
                      v-model="rule_algorithm_now.value" placeholder="清选择">
                      <el-option v-for="item in rule_algorithm" :key="item.label" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                  <div>
                    <el-input size="small" style="width: 130px;" v-model="setRulePrice" placeholder="请输入调价参数"
                      @blur="setRulePrice_ToTable"></el-input>
                  </div>
                </div>
                <!-- END规则调价 -->
              </div>
              <!-- 表格 -->
              <div class="setPrice_price_table">
                <el-table :data="setPriceTableData" :header-cell-style="{ background: '#ebeef5', color: 'black' }"
                  style="width: 100%;border: 1px solid #dddddd;">
                  <el-table-column prop="room_title" label="本地房型" fixed="left">
                  </el-table-column>
                  <el-table-column v-for="(item, index) in checkedChannel_obj" :key="index" :label="item.name">
                    <template slot-scope="scope">
                      <div class="setPrice_price_table_slot">
                        {{ item.name }}
                        <div class="input_price">
                          <el-input size="small" v-show="type == 1" style="width: 80px;"
                            v-model="setPriceTableData[scope.$index].room_prices[index]" placeholder="金额">
                            <span slot="prefix">￥</span>
                          </el-input>
                          <div v-show="type == 2" style="display: flex;">
                            {{ rule_algorithm_now.rule }}
                            <el-input size="small" style="width: 80px;margin-left: 10px;"
                              v-model="setPriceTableData[scope.$index].room_prices[index]" placeholder="调参">
                            </el-input>
                          </div>
                        </div>

                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" fixed="right">
                    <template slot-scope="scope">
                      <el-button size="mini" style="color: red;" type="text"
                        @click="handleDelete_TableRoomType(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <!-- 提交底部 -->
              <div class="setPrice_price_bottom">
                <div class="setPrice_price_bottom_group">
                  <el-button @click="cleardate">取消</el-button>
                  <el-button type="primary" @click="submit">确定</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import { GetAllRoomType, batchPrice_room } from '@/api/hotel'
import { getChannel } from '@/api/channel'
import { calculateTotalTime } from './../../../../api/countDay'//计算日期差（天数
export default {
  name: 'BatchSetting',
  components: {
  },
  data() {
    return {
      hotel_id: sessionStorage.getItem('hotel_id'),
      type: 1,//改价方式，1指定金额 2 规则调价
      channels: [],//所有渠道数组
      checkedChannel_obj: [],//所有渠道数组
      roomType: [],//所有房型
      weeks: [//所有周*
        {
          week_title: '周一',
          week_id: 1
        },
        {
          week_title: '周二',
          week_id: 2
        },
        {
          week_title: '周三',
          week_id: 3
        },
        {
          week_title: '周四',
          week_id: 4
        },
        {
          week_title: '周五',
          week_id: 5
        },
        {
          week_title: '周六',
          week_id: 6
        },
        {
          week_title: '周日',
          week_id: 7
        },
      ],
      isAllCheckChannel: false,//是否选中全部渠道
      isAllCheckRoom: false,
      isAllCheckWeek: false,
      checkedChannel: [],//渠道多选按钮绑定值，选中的数组(渠道名称)
      checkedRoom: [],//房型多选按钮绑定值，选中的数组(房型名称)
      checkedWeek: [],//week多选按钮绑定值，选中的数组(week名称)
      channel_id: [],//选中的渠道id数组
      room_id: [],//选中的房型id
      week_id: [],//选中的周*id
      dateRange: [[]],//日期段数组
      selectDays: 0,//计算日期段数组得到的时间
      setPriceTableData: [],//设置价格表格数据
      setAppointPrice: null,//指定金额
      setRulePrice: null,//规则金额
      rule_channel_value: 1,//改价渠道值
      rule_algorithm_now: {},//选中的规则改价算法
      rule_algorithm: [//规则改价算法
        {
          rule: '+',
          label: '加',
          value: 1
        },
        {
          rule: '-',
          label: '减',
          value: 2
        },
        {
          rule: '*',
          label: '乘',
          value: 3
        },
        {
          rule: '/',
          label: '除',
          value: 4
        }
      ],
    }
  },
  created() {
    this.getAllChannel()//获取渠道
  },
  methods: {
    /**获取渠道 */
    getAllChannel() {
      let getChannelData = {
        hotel_id: sessionStorage.getItem('hotel_id')
      }
      getChannel(getChannelData).then(res => {
        let { code, data } = res.data
        if (200 == code) {
          this.channels = data
          this.rule_channel_value = this.channels[0].channel_id
          this.rule_algorithm_now = this.rule_algorithm[0]
        }
      })
    },
    /**获取房型 */
    getRoom() {
      let getAllRoomData = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        channel_id: this.channel_id
      }
      GetAllRoomType(getAllRoomData).then(res => {
        let { code, data } = res.data
        if (200 == code) {
          this.roomType = data
        }
        // console.log(this.roomType, 'GetAllRoomType');
      })
    },
    /**
     *  渠道全选按钮
     * @param {*} val  渠道全选按钮状态
     */
    checkAllChannel(val) {
      let arr = []
      this.channels.forEach(item => {
        arr.push(item.name)
      })
      this.checkedChannel = val ? arr : []
    },
    /**
     *  房型全选按钮
     * @param {*} val  房型全选按钮状态
     */
    checkAllRoom(val) {
      let arr = []
      this.roomType.forEach(item => {
        arr.push(item.pms_title)
      })
      this.checkedRoom = val ? arr : []
    },
    /**
    *  周*全选按钮
    * @param {*} val  周*全选按钮状态
    */
    checkAllWeek(val) {
      let arr = []
      this.weeks.forEach(item => {
        arr.push(item.week_title)
      })
      this.checkedWeek = val ? arr : []
    },
    /**
     * 多选按钮组选中的值 改变事件
     * @param {*} value 多选按钮组选中的值 
     */
    handleCheckedChannelsChange(value) {
      if (value.length == this.channels.length) {
        this.isAllCheckChannel = true
      } else {
        this.isAllCheckChannel = false
      }
    },
    handleCheckedRoomsChange(value) {
      if (value && value.length == this.roomType.length) {
        this.isAllCheckRoom = true
      } else {
        this.isAllCheckRoom = false
      }
    },
    handleCheckedWeeksChange(value) {
      if (value && value.length == this.weeks.length) {
        this.isAllCheckWeek = true
      } else {
        this.isAllCheckWeek = false
      }
    },
    /**
     * 删除表格房型/取消选中房型
     * @param {*} row 
     */
    handleDelete_TableRoomType(row) {
      this.checkedRoom.forEach((item, index) => {
        if (row.room_title == item) {
          this.checkedRoom.splice(index, 1)
        }
      })
    },
    // 添加日期段
    addDateRange() {
      if (this.dateRange.length == 10) {
        this.$message.warning('最多添加十个日期段!');
      } else {
        this.dateRange.push([])
      }
    },
    /**
     * 设置指定金额到表格内输入框
     * 失去焦点事件
     */
    setAppointPrice_ToTable() {
      this.setPriceTableData.forEach(item => {
        item.room_prices = item.room_prices.map(element => this.setAppointPrice);
      })
    },
    /**
    * 设置规则调参金额到表格内输入框
    * 失去焦点事件
    */
    setRulePrice_ToTable() {
      console.log(this.setRulePrice, 'setRulePrice');
      this.setPriceTableData.forEach(item => {
        item.room_prices = item.room_prices.map(element => this.setRulePrice);
      })
    },
    /**
     * 规则调价--算法改变事件
     * @param {*} val 
     */
    rule_algorithmChange(val) {
      this.rule_algorithm.forEach(item => {
        if (item.value == val) {
          this.rule_algorithm_now = item
        }
      })
    },
    /**
   * 规则调价--渠道价格改变事件
   * @param {*} val 
   */
    rule_channelChange(val) {
      this.rule_channel_value = val
    },
    /**
     * 重置
     */
    reset(val) {
      if ('channel' == val) {
        this.isAllCheckChannel = false
        this.checkedChannel = []
      } else if ('room' == val) {
        this.isAllCheckRoom = false
        this.checkedRoom = []
      } else if ('date' == val) {
        this.isAllCheckWeek = false
        this.checkedWeek = []
        this.dateRange = [[]]
      }
    },
    // 取消按钮  清空数据
    cleardate() {
      this.isAllCheckChannel = false
      this.isAllCheckWeek = false
      this.isAllCheckRoom = false
      this.checkedChannel = []
      this.checkedWeek = []
      this.dateRange = [[]]
      this.type = 1
      this.setAppointPrice = null
      this.setRulePrice = null
    },

    // 确定
    submit() {
      let info = []
      this.setPriceTableData.forEach(item => {
        item.price = []
        item.room_channel_ids.forEach((items, index) => {
          item.price.push({
            channel_id: items,
            price: item.room_prices[index]
          })
        })
        info.push({
          symbol: item.symbol,
          room_id: item.room_id,
          price: item.price
        })
      })
      this.dateRange = this.dateRange.filter(item => item.length != 0)
      let batch_price_Data = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        channel_id: this.channel_id,
        type: this.type,
        week: this.week_id,
        dates: this.dateRange,
        channel_price_id: this.rule_channel_value,
        room_info: info
      }
      console.log(batch_price_Data, 'batch_price_Data');
      batchPrice_room(batch_price_Data, 'PUT').then(res => {
        console.log(res.data, '批量修改价格结果');
        let { code, message } = res.data
        if (200 == code) {
          this.$message.success(message)
          this.cleardate()
        } else {
          this.$message.error(message)
        }
      })
    },


  },
  watch: {
    checkedChannel(newArr) {
      let arr = []//选中的id数组
      this.checkedChannel_obj = []
      this.channels.forEach(item => {
        newArr.forEach(items => {
          if (item.name == items) {
            arr.push(item.channel_id)
            this.checkedChannel_obj.push(item)
          }
        })
      })
      this.channel_id = arr.join(',')
      this.checkedRoom = []
      if (newArr.length > 0) {
        this.getRoom()
      } else {
        this.roomType == []
      }
    },
    // 房型id、
    checkedRoom(newArr) {
      if (newArr.length == 0) {
        this.isAllCheckRoom = false
      }
      this.room_id = []
      this.setPriceTableData = []

      let setPriceTableData_channel_id = []
      // 得到接口参数的room_info的price数组
      this.checkedChannel_obj.forEach(item => {
        setPriceTableData_channel_id.push(item.channel_id)
      })

      // this.priceArr = setPriceTableData_priceArr
      this.roomType.forEach(item => {
        newArr.forEach(items => {
          if (items == item.pms_title) {
            this.room_id.push(item)
            this.setPriceTableData.push({
              symbol: this.rule_algorithm_now.value,
              room_id: item.id,
              room_title: item.pms_title,
              room_channel_ids: setPriceTableData_channel_id,
              room_prices: []
            })
          }
        })
      })
      // 根据id来对应价格
      this.setPriceTableData.forEach(item => {
        for (let i = 0; i < item.room_channel_ids.length; i++) {
          item.room_prices.push(undefined)
        }
      })
    },
    checkedWeek(newArr) {
      let arr = []//选中的id数组
      this.weeks.forEach(item => {
        newArr.forEach(items => {
          if (item.week_title == items) {
            arr.push(item.week_id)
          }
        })
      })
      this.week_id = arr.join(',')
    },
    dateRange(n) {
      this.selectDays = calculateTotalTime(this.dateRange)
    },
    //切换时调价方式时清空数据
    type() {
      this.setPriceTableData.forEach(item => {
        item.room_prices = item.room_prices.map(element => undefined);
      })
      this.setRulePrice = undefined
      this.setAppointPrice = undefined
    }
  },
  computed: {

  },
}
</script>

<style lang="scss" scoped>
#batch {
  font-size: 16px;
}

.content {
  .overflow-auto {
    width: 100%;
    // height: 100%;
    .body {
      width: 90%;
      padding: 20px;
      height: calc(100vh - 160px);
      overflow: auto;

      .reminder {
        padding: 0px 15px;
        width: 95%;
        background: #fff7e6;
        border: 1px solid #e6a23c;
        border-radius: 2px;
        height: auto;
        line-height: 40px;
        display: flex;
        justify-content: space-between;
      }

      .select {
        // background-color: #bcfdb5;
        padding: 20px 0;

        .select_top {
          display: flex;
          margin: 15px 0;

          .select_num {
            border: 1px solid #0486fe;
            height: 30px;
            line-height: 30px;
            margin-right: 10px;
            padding: 0px 15px;
          }
        }

        .select_checkbox {
          background-color: white;
          padding: 25px;
          display: flex;
          line-height: 32px;

          div {
            margin-right: 20px;
          }
        }
      }

      .select_date {
        background-color: white;
        padding: 25px;

        .select_date_time {
          display: flex;

          .select_date_select {
            margin-left: 20px;

            .select_date_picker {
              margin-bottom: 15px;

              .select_date_picker_item {
                margin-bottom: 15px;
              }
            }

            .select_date_addTime {
              margin-top: -15px;

              span {
                font-size: 12px;
                color: #a1a0a0;
                margin-left: 10px;
              }
            }
          }
        }
      }

      .setPrice {
        background-color: white;
        padding: 25px;
        margin-top: 20px;

        .setPrice_type {
          display: flex;
          padding: 15px 0;

          .setPrice_type_radio {
            margin-left: 25px;
          }
        }

        .setPrice_price {
          // background-color: #ebeef5;
          background-color: #F7FAFF;
          padding: 10px 20px;
          display: flex;
          line-height: 32px;
          height: 35px;

          .setPrice_price_appoint {
            margin-left: 20px;


            span {
              font-size: 16px;
              color: black;
            }
          }

          .setPrice_price_rule {
            display: flex;
            margin-left: 20px;

            div {
              margin-right: 10px;
            }
          }
        }

        .setPrice_price_table {
          margin: 20px 0;
        }

        .setPrice_price_bottom {
          margin-top: 20px;
          height: 40px;

          .setPrice_price_bottom_group {
            float: right;
          }
        }
      }
    }
  }
}

.setPrice_price_table_slot {
  display: flex;
  line-height: 32px;

  .input_price {
    width: 80px;
    margin-left: 15px;
    display: inline-block;

    span {
      line-height: 32px;
    }
  }
}

// ￥符号
::v-deep .el-icon-my-money {
  background: url("../../../../assets/images/￥.png") center center no-repeat;
  background-size: 12px;
}
</style>